package 双指针;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 三数之和7 {
    //https://leetcode.cn/problems/3sum/description/
    public List<List<Integer>> threeSum(int[] nums) {
        int cur = 0;
        Arrays.sort(nums);
        //List<List<Integer>> ret = new LinkedList<>();
        List<List<Integer>> ret = new ArrayList<>();
        while(cur < nums.length - 2 && nums[cur] <= 0) {
            int target = -nums[cur];
            int left = cur + 1, right = nums.length - 1;
            while(left < right) {
                if(nums[left] + nums[right] > target) {
                    int same = nums[right--];
                    while(left < right && nums[right] == same) {
                        right--;
                    }
                }else if(nums[left] + nums[right] < target) {
                    int same = nums[left++];
                    while(left < right && nums[left] == same) {
                        left++;
                    }
                }else {
                    //List<Integer> tmp = new LinkedList<>();
                    //tmp.add(nums[cur]);
                    //tmp.add(nums[left]);
                    //tmp.add(nums[right]);
                    //ret.add(tmp);
                    ret.add(new ArrayList<Integer>(Arrays.asList(nums[cur],nums[left],nums[right])));
                    //int sameleft = nums[left++], sameright = nums[right--];
                    left++;
                    right--;
                    while(left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                    while(left < right && nums[right] == nums[right + 1]) {
                        right--;
                    }
                }
            }
            //int tmpcur = nums[cur++];
            cur++;
            while(cur < nums.length && nums[cur] == nums[cur - 1] && nums[cur] <= 0) {
                cur++;
            }
        }
        return ret;
    }
}
